import 'dart:math' as math;
import 'dart:ui';

import 'package:flame/collisions.dart';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flamedemo/component/Border.dart';
import 'package:flutter/material.dart';

class Ball extends CircleComponent
    with HasGameReference<FlameGame>, CollisionCallbacks {
  Vector2 velocity = Vector2.zero();
  bool isStart = true;

  late CircleHitbox circleHitbox;
  Ball() {
    paint = Paint()..color = Colors.white;
    radius = 10;
  }

  static const double speed = 500;
  static const degree = math.pi / 180;

  @override
  Future<void> onLoad() async {
    super.onLoad();
    anchor = Anchor.center;
    circleHitbox = CircleHitbox(
      radius: radius,
    );
    add(circleHitbox);
  }

  @override
  void update(double dt) {
    super.update(dt);
    if (isStart) {
      position += velocity * dt;
    }
  }

  double get getSpawnAngle => lerpDouble(0, 360, math.Random().nextDouble())!;
  @override
  void onCollisionStart(
      Set<Vector2> intersectionPoints, PositionComponent other) {
    super.onCollisionStart(intersectionPoints, other);
    if (other is MyBorder) {
      final collisionPoint = intersectionPoints.first;
      if (collisionPoint.x <= other.x) {
        velocity.x = -velocity.x;
        velocity.y = velocity.y;
      }
      if (collisionPoint.y <= other.y) {
        velocity.x = velocity.x;
        velocity.y = -velocity.y;
      }
      if (collisionPoint.x >= other.width + other.x) {
        velocity.x = -velocity.x;
        velocity.y = velocity.y;
      }
      if (collisionPoint.y >= other.height + other.y) {
        velocity.x = velocity.x;
        velocity.y = -velocity.y;
      }
    }
  }
}
